﻿using Learun.Util;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-02-23 11:30
    /// 描 述：属性表
    /// </summary>
    public class ec_propertyService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_propertyEntity> _propertyRepository => new Repository<ec_propertyEntity>();
        Repository<ec_objecttypepEntity> _objecttypepRepository => new Repository<ec_objecttypepEntity>();
        Repository<ec_dataitemdetailEntity> _dataitemdetailRepository => new Repository<ec_dataitemdetailEntity>();
        #endregion
        #region 获取数据
        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_propertyEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    return _propertyRepository.GetById(keyValue);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    var strSql = new StringBuilder();
                    strSql.Append($@"SELECT * FROM ec_property_{ProjectEntity.ProjectIndex} WHERE PropertyID = @PropertyID ");
                    //List<ec_propertyEntity> list = this.BaseRepository().FindList<ec_propertyEntity>(strSql.ToString(), new { PropertyID = keyValue }).ToList();
                    //return list.FirstOrDefault();
                    return SqlSugarHelper.Db.Ado.SqlQuerySingle<ec_propertyEntity>(strSql.ToString(), new { PropertyID = keyValue });
                }

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取树形数据
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        public DataTable GetSqlTree(string ProjectId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    //return this.BaseRepository().FindTable($" SELECT t.* FROM ec_propertyg t WHERE 1=1 ORDER BY t.OrderID ");
                    return SqlSugarHelper.Db.Ado.GetDataTable($" SELECT t.* FROM ec_propertyg t WHERE 1=1 ORDER BY t.OrderID ");
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    //return this.BaseRepository().FindTable($" SELECT t.* FROM ec_propertyg_{ProjectEntity.ProjectIndex} t WHERE 1=1 ORDER BY t.OrderID ");
                    return SqlSugarHelper.Db.Ado.GetDataTable($" SELECT t.* FROM ec_propertyg_{ProjectEntity.ProjectIndex} t WHERE 1=1 ORDER BY t.OrderID ");
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        /// <summary>
        /// 获取树形数据
        /// </summary>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        public IEnumerable<ec_propertyEntity> GetSqlPropTree(string ProjectId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId) || ProjectId == "0")
                {
                    return SqlSugarHelper.Db.SqlQueryable<ec_propertyEntity>(@" 
                                                                    SELECT t1.*,t2.PropertyGroupName FROM ec_property t1
                                                                    LEFT JOIN ec_propertyg t2 ON t1.PropertyGID = t2.PropertyGID 
                                                                    ORDER BY t2.OrderID,t1.OrderID").ToList();
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    return SqlSugarHelper.Db.SqlQueryable<ec_propertyEntity>($@" 
                                                         SELECT t1.*,t2.PropertyGroupName FROM ec_property_{ProjectEntity.ProjectIndex} t1
                                                         LEFT JOIN ec_propertyg_{ProjectEntity.ProjectIndex} t2 ON t1.PropertyGID = t2.PropertyGID
                                                         ORDER BY t2.OrderID,t1.OrderID").ToList();
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    _propertyRepository.Delete(t => t.PropertyID == keyValue);
                    _objecttypepRepository.Delete(t => t.PropertyID == keyValue);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    SqlSugarHelper.Db.Ado.ExecuteCommand($@" DELETE FROM ec_property_{ProjectEntity.ProjectIndex} WHERE PropertyID = '{keyValue}'; 
                                        DELETE FROM ec_objecttypep_{ProjectEntity.ProjectIndex} WHERE PropertyID = '{keyValue}';
                                    ");
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_propertyEntity entity, string ProjectId)
        {
            try
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    entity.Modify(keyValue);
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _propertyRepository.Update(entity);
                    }
                    else
                    {
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        //this.BaseRepository().UpdateByNoMap(entity, $"ec_property_{ProjectEntity.ProjectIndex}", "PropertyID");
                        _propertyRepository.AsUpdateable(entity).AS($"ec_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();

                        //同时修改，命名规则里的名字
                    }
                }
                else
                {
                    entity.Create();
                    if (string.IsNullOrWhiteSpace(ProjectId))
                    {
                        _propertyRepository.Insert(entity);
                    }
                    else
                    {
                        var ProjectEntity = _projectRepository.GetById(ProjectId);
                        //this.BaseRepository().InsertByNoMap(entity, $"ec_property_{ProjectEntity.ProjectIndex}");
                        _propertyRepository.AsInsertable(entity).AS($"ec_property_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

    }
}
